//
//  PortraitPresentationController.m
//  UIViewControllerTransitionDemo
//
//  Created by Guo Rui on 2017/7/5.
//  Copyright © 2017年 GR Harry. All rights reserved.
//

#import "PortraitPresentationController.h"

@interface PortraitPresentationController ()
@property (strong, nonatomic) UIView *dimmingView;
@end

@implementation PortraitPresentationController

- (instancetype)initWithPresentedViewController:(UIViewController *)presentedViewController presentingViewController:(UIViewController *)presentingViewController
{
    self = [super initWithPresentedViewController:presentedViewController presentingViewController:presentingViewController];
    if (self) {
        self.dimmingView = [[UIView alloc] init];
        self.dimmingView.backgroundColor = [UIColor blackColor];
    }
    return self;
}

- (void)presentationTransitionWillBegin {
    self.dimmingView.frame = self.containerView.bounds;
    [self.containerView addSubview:self.dimmingView];
    
    self.dimmingView.alpha = 0.f;
    
    [self.presentedViewController.transitionCoordinator animateAlongsideTransition:^(id<UIViewControllerTransitionCoordinatorContext>  _Nonnull context) {
       
        self.dimmingView.alpha = .7f;
        self.presentingViewController.view.transform = CGAffineTransformMakeScale(.9f, .9f);
    } completion:^(id<UIViewControllerTransitionCoordinatorContext>  _Nonnull context) {
        
    }];
}

- (void)presentationTransitionDidEnd:(BOOL)completed {
    if (!completed) {
        [self.dimmingView removeFromSuperview];
        self.presentingViewController.view.transform = CGAffineTransformIdentity;
    }
}

- (void)dismissalTransitionWillBegin {
    [self.presentedViewController.transitionCoordinator animateAlongsideTransition:^(id<UIViewControllerTransitionCoordinatorContext>  _Nonnull context) {
        self.presentingViewController.view.transform = CGAffineTransformIdentity;
        self.dimmingView.alpha = 0;
    } completion:^(id<UIViewControllerTransitionCoordinatorContext>  _Nonnull context) {

    }];
}

- (void)dismissalTransitionDidEnd:(BOOL)completed {
    if (completed) {
        [self.dimmingView removeFromSuperview];
    }
    else {
        self.presentingViewController.view.transform = CGAffineTransformMakeScale(.9f, .9f);
    }
}

- (CGRect)frameOfPresentedViewInContainerView {
    CGRect rect = self.containerView.bounds;
    rect.origin.y = 200;
    rect.size.height -= 200;
    return rect;
}

- (UIView *)presentedView {
    self.presentedViewController.view.layer.cornerRadius = 8.f;
    self.presentedViewController.view.layer.masksToBounds = YES;
    
    return self.presentedViewController.view;
}

- (void)dealloc {
    
    NSLog(@"\n************\n %@ dealloc \n************", self.class);
}

@end
